﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommonTagTime.Business;
using CommonTagTime.ModelObject;
using CommonTagTime;
using System.IO;
using System.Drawing;
using System.Web.UI.HtmlControls;


public partial class admin_CountryDetail : SitePage
{
    public string html = string.Empty;
    private CountryAreaCategoryCollection lstCate = new CountryAreaCategoryCollection();
    #region Fields
    public string Command
    {
        get
        {
            object o = ViewState["Command"];
            if (o != null) return (string)o;
            return string.Empty;
        }
        set { ViewState["Command"] = value; }

    }
   
    public int CountryId
    {
        get
        {
            object o = ViewState["CountryId"];
            if (o != null) return (int)o;
            return int.MinValue;
        }
        set { ViewState["CountryId"] = value; }

    }
    #endregion

    #region Init,Load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadData();
            LoadDataCategory();
        }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        InitData();       
    } 
    
    protected override void OnInitComplete(EventArgs e)
    {
        base.OnInitComplete(e);

    }
    #endregion

    #region Methods
    private void LoadData()
    {
        if (this.Command == "edit")
        {
            busCountry objBus = new busCountry();
            Country objCountry = objBus.GetById(this.CountryId);
            if (objCountry != null)
            {
                txtCode.Text = objCountry.CountryCode.Trim();
                if (objCountry.IsActive)
                    chkIsActive.Checked = true;
                else chkIsActive.Checked = false;               
                txtName.Text = objCountry.CountryName;
                busCountryAreaCategory objBusCate = new busCountryAreaCategory();
                lstCate = objBusCate.GetByCountryId(this.CountryId);
            }
        }
    }
    private void InitData()
    {
        string validateGroup = "countryDetail";
        vsumForm.ValidationGroup = btnSave.ValidationGroup = reqCode.ValidationGroup = reqName.ValidationGroup = validateGroup;
        //Init message
        reqCode.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Code");
        reqName.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Name");
        this.Command = clsQueryString.GetString("act");
        this.CountryId = clsQueryString.GetInt("id");     
    }  
    private string GetSelectCheckBoxCategory(int cateId)
    {
        foreach (CountryAreaCategory objCate in lstCate)
        {
            if (objCate.AreaCategoryId == cateId)
            {
                lstCate.Remove(objCate);
                hidCategoryIDSelect.Value += cateId + ";";
                return "checked='checked'";
            }
        }
        return string.Empty;
    }
    private void LoadDataCategory()
    {
        bool isExpand = true;
        //Get VideoCategory
        hidCategoryIDSelect.Value = string.Empty;
        //Load all Catgeory in Level 1
        Category objCondition = new Category();
        objCondition.OrderBy = busCategory.SORTORDER;
        objCondition.OrderDirection = "ASC";
        objCondition.CurrentPage = 1;
        objCondition.PageSize = int.MaxValue;
        objCondition.Condition = " ParentId is null and Type=" + (byte)enmCategoryType.Area;
        busCategory objBus = new busCategory();
        CategoryCollection lstLevel1 = objBus.List(objCondition);//only return one object
        if (lstLevel1 != null && lstLevel1.Count > 0)
        {
            html = @"<table cellspacing='0' cellpadding='0' border='0'>
                        <tr>
                            <td style='padding:0px;'>
                                  <img height='22' width='16' src='../App_Themes/Admin/images/icons/folderplus2.gif' id='FFLD" + lstLevel1[0].CategoryID + @"'>
                            </td>
                            <td style='padding:0px;'>
                                    <img height='16' width='4' src='../App_Themes/Admin/images/icons/spacer.gif'>
                            </td>
                           
                            <td nowrap='' style='padding:0px;'>
                                    <a href='javascript:void(0);' onClick=SelectCateName(" + lstLevel1[0].CategoryID + @")>" + lstLevel1[0].Name + @"</a>
                            </td>
                            </tr>
                       </table>";
            CategoryCollection lstChild = GetChild(lstLevel1[0]);
            for (int i = 0; i < lstChild.Count; i++)
            {
                Category objBreadCrum = lstChild[i];
                if (i == lstChild.Count - 1)
                    html += BuildHTML(objBreadCrum, true, isExpand);
                else html += BuildHTML(objBreadCrum, false, isExpand);
            }
        }
        lblCate.Text = html;
    }
    private CategoryCollection GetChild(Category objData)
    {
        Category objCondition = new Category();
        objCondition.OrderBy = busCategory.SORTORDER;
        objCondition.OrderDirection = "ASC";
        objCondition.Condition = " ParentId=" + objData.CategoryID;
        objCondition.CurrentPage = 1;
        objCondition.PageSize = int.MaxValue;
        busCategory objBus = new busCategory();
        CategoryCollection lstResult = objBus.List(objCondition);
        return lstResult;
    }
    private string BuildHTML(Category objData, bool lastNode, bool isExpand)
    {
        string tdPadding = string.Empty;
        string result = string.Empty;
        for (int i = 2; i < objData.Level; i++)
        {
            tdPadding += @" <td style='padding:0px;'>
                    <img height='22' width='19' src='../App_Themes/Admin/images/icons/i2.gif'>
                </td>";
        }

        //get list child for this object
        CategoryCollection lstChild = GetChild(objData);
        if (lstChild != null && lstChild.Count > 0)
        {
            string folderexpand = string.Empty;
            string expandImage = string.Empty;
            if (objData.Level > 1 && lastNode)
            {
                expandImage = "  <img height='22' width='19' id='IMG" + objData.CategoryID + @"' src='../App_Themes/Admin/images/icons/lplus2.gif'>";
            }
            else
            {
                if (isExpand)
                {
                    folderexpand = "folderminus2.gif";
                    expandImage = "  <img height='22' width='19' id='IMG" + objData.CategoryID + @"' src='../App_Themes/Admin/images/icons/tminus2.gif'>";
                }
                else
                {
                    folderexpand = "folderplus2.gif";
                    expandImage = "  <img height='22' width='19' id='IMG" + objData.CategoryID + @"' src='../App_Themes/Admin/images/icons/tplus2.gif'>";
                }
            }
            // expandImage = "  <img height='22' width='19' id='IMG" + objData.CategoryID + @"' src='../App_Themes/Admin/images/icons/lplus2.gif'>";
            result += @"<table cellspacing='0' cellpadding='0' border='0'>
            <tr>
                " + tdPadding + @"
                <td  onclick=expandit(" + objData.CategoryID + @") style='padding:0px;'>
                    " + expandImage + @"
                </td>
                <td style='padding:0px;'>
                    <img height='22' width='16' id='FLD" + objData.CategoryID + @"' src='../App_Themes/Admin/images/icons/" + folderexpand + @"'>
                </td>
                <td width='4' style='padding:0px;'>
                    <img height='16' width='4' src='../App_Themes/Admin/images/icons/spacer.gif'>
                </td>
                <td style='padding:0px;'>
                    <img height='16' width='4' src='../App_Themes/Admin/images/icons/spacer.gif'>
                </td>
                <td nowrap='' style='padding:0px;'>
                    <a href='javascript:void(0);' onClick=SelectCateName(" + objData.CategoryID + @")>" + objData.Name + @"</a>
                </td>
            </tr>
        </table>";
            if (isExpand)
                result += "<span id='SPAN" + objData.CategoryID + "' style='display:block;'>";
            else result += "<span id='SPAN" + objData.CategoryID + "' style='display: none;'>";
            for (int index = 0; index < lstChild.Count; index++)
            {
                Category objBreadCrum = lstChild[index];
                if (index == lstChild.Count - 1)
                    result += BuildHTML(objBreadCrum, true, isExpand);
                else result += BuildHTML(objBreadCrum, false, isExpand);
            }
            result += "</span>";
        }
        else
        {
            string expandImage = string.Empty;
            if (lastNode)
            {
                expandImage = "  <img height='22' width='19'  src='../App_Themes/Admin/images/icons/l2.gif'>";
            }
            else expandImage = "  <img height='22' width='19'  src='../App_Themes/Admin/images/icons/t2.gif'>";

            result = @"<table cellspacing='0' cellpadding='0' border='0'>
            <tr>
                " + tdPadding + @"
                <td style='padding:0px;'>
                   " + expandImage + @"
                </td>
                <td style='padding:0px;'>
                    <img height='22' width='16' src='../App_Themes/Admin/images/icons/folderplus2.gif'>
                </td>
                <td width='4' style='padding:0px;'>
                    <img height='16' width='4' src='../App_Themes/Admin/images/icons/spacer.gif'>
                </td>
                <td style='padding:0px;'>
                    <img height='16' width='4' src='../App_Themes/Admin/images/icons/spacer.gif'>
                </td>
                <td nowrap='' style='padding:0px;'>
                    <input type='radio' name='rdoCate' id='chkCategory_" + objData.CategoryID + @"' " + GetSelectCheckBoxCategory(objData.CategoryID) + @"  onclick=CheckCategoryItem(" + objData.CategoryID + @",this.checked); />
                    <a href='javascript:void(0);' onClick=SelectCateName(" + objData.CategoryID + @")>" + objData.Name + @"</a>
                </td>
            </tr>
        </table>";
        }
        return result;
    }
    private void InsertCategory(int countryId, bool isUpdate)
    {
        busCountryAreaCategory objBus = new busCountryAreaCategory();
        //delete old Category
        if (isUpdate)
        {
            objBus.DeleteByCountryId(countryId);
        }
        string[] cate = hidCategoryIDSelect.Value.Split(';');
        if (cate.Length > 0)
        {
            int cateID;
            foreach (string s in cate)
            {
                cateID = clsConvert.Int(s);
                if (cateID > 0)
                {
                    CountryAreaCategory objData = new CountryAreaCategory();
                    objData.CountryID = countryId;
                    objData.AreaCategoryId = cateID;
                    objBus.Insert(objData);
                }
            }
        }
    }
    private void UpdateCountry(Country objData)
    {
        busCountry objBus = new busCountry();
        objData.CountryID = this.CountryId;
        int result=objBus.Update(objData);
        if (result==-1)
             lblErrorMessage.Text = string.Format(Resources.Resource.MSG_CHECK_EXISTS, "Code");
        else if (result == 0)
            lblErrorMessage.Text = Resources.Resource.MSG_UPDATE_ERROR;
        else
        {            
            InsertCategory(objData.CountryID, true);
            Response.Redirect("CountryList.aspx?" + this.GetPageQuery);
        }
        Page.RegisterStartupScript("CheckCate", "<script>CheckCate();</script>");
    }

    private void InsertCountry(Country objCountry)
    {
        busCountry objBus = new busCountry();
        int result=objBus.Insert(objCountry);
        if (result == -1)
            lblErrorMessage.Text = string.Format(Resources.Resource.MSG_CHECK_EXISTS, "Code");
        else if (result == 0)
            lblErrorMessage.Text = Resources.Resource.MSG_INSERT_ERROR;
        else
        {
            InsertCategory(result, false);
            Response.Redirect("CountryList.aspx?" + this.GetPageQuery);
        }
        Page.RegisterStartupScript("CheckCate", "<script>CheckCate();</script>");
    }
    #endregion

    #region Events

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            //get datavalue
            Country objData = new Country();              
            if (chkIsActive.Checked)
                objData.IsActive = true;
            else
                objData.IsActive = false;
            objData.CountryCode = txtCode.Text;
            objData.CountryName = txtName.Text;           
            if (this.Command == "edit")
                UpdateCountry(objData);
            else
                InsertCountry(objData);
        }
        else
        {
            vsumForm.ShowMessageBox = false;
            vsumForm.ShowSummary = true;
        }
    }    
    
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("CountryList.aspx?" + this.GetPageQuery);
    }     
    #endregion   
}